package com.rlax.framework.interceptor;

import java.util.Date;

import org.apache.shiro.SecurityUtils;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.rlax.framework.common.Consts;
import com.rlax.framework.common.Status;
import com.rlax.framework.util.CommonUtils;
import com.rlax.framework.util.DateUtils;
import com.rlax.web.base.BaseController;
import com.rlax.web.model.Log4s;
import com.rlax.web.model.User4s;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;

/**
 * 日志拦截器，记录系统操作日志
 * 
 * @author Rlax
 *
 */
public class Log4sInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		if (inv.getController() instanceof BaseController) {
			BaseController c = (BaseController) inv.getController();
			
			User4s user = null;
			if (SecurityUtils.getSubject().isAuthenticated()) {
				user = (User4s) c.getSession().getAttribute(Consts.SESSION_USER);
			}
			
			UserAgent userAgent = UserAgent.parseUserAgentString(c.getRequest().getHeader("User-Agent"));
			Browser browser = userAgent.getBrowser();

			// 1.访问 2 登录 3.添加 4. 编辑 5. 删除
			String operation = "1";
			if (c.getRequest().getRequestURI().contains("do_add")) {
				operation = "3";
			} else if (c.getRequest().getRequestURI().contains("do_update")) {
				operation = "4";
			} else if (c.getRequest().getRequestURI().contains("do_delete")) {
				operation = "5";
			} else if (c.getRequest().getRequestURI().contains("do_login")) {
				operation = "2";
			}
			
			Log4s log = new Log4s();
			log.setUid(user == null ? null : user.getId());
			log.setBrowser(browser.getName());
			log.setOperation(operation);
			log.setFrom(c.getRequest().getHeader("Referer"));
			log.setIp(CommonUtils.getRequsetIp(c.getRequest()));
			log.setUrl(c.getRequest().getRequestURI());
			log.setStatus(Status.COMMON_USE);
			log.setCreateDate(new Date());
			log.setLastUpdAcct(user == null ? "guest" : user.getName());
			log.setLastUpdTime(DateUtils.getDateTime());
			log.setNote("记录日志");
			log.save();
		}
		inv.invoke();
	}

}
